﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IterationLife.Domains.Sports.Configs;
using IterationLife.Domains.Sports.Dtos.ZeppSports;
using IterationLife.Domains.Sports.Models;
using IterationLife.Domains.Sports.Repositories;
using IterationLife.Extensions.HttpRequest;
using Util.Domains;

namespace IterationLife.Domains.Sports.Services
{
    public class ZeppDataSerializable : DomainServiceBase, IZeppDataSerializable
    {
        public ZeppDataSerializable(ISportEventGroupPersonRepository sportEventGroupPersonRepository, ISportEventGroupRepository sportEventGroupRepository, ISportAthleteRepository sportAthleteRepository, ISportUserRepository sportUserRepository, ISportTeamRepository sportTeamRepository, ISportEventRepository sportEventRepository)
        {
            SportUserRepository = sportUserRepository;
            SportTeamRepository = sportTeamRepository;
            SportEventRepository = sportEventRepository;
            SportAthleteRepository = sportAthleteRepository;
            SportEventGroupRepository = sportEventGroupRepository;
            SportEventGroupPersonRepository = sportEventGroupPersonRepository;
        }
        protected ISportUserRepository SportUserRepository { get; set; }

        protected ISportTeamRepository SportTeamRepository { get; set; }

        protected ISportEventRepository SportEventRepository { get; set; }
        protected ISportAthleteRepository SportAthleteRepository { get; set; }
        protected ISportEventGroupRepository SportEventGroupRepository { get; set; }
        protected ISportEventGroupPersonRepository SportEventGroupPersonRepository { get; set; }

        #region 导入用户

        /// <summary>
        /// 数据用户
        /// </summary>
        public SportUser ImportUser(ZeppUserInfo userInfo)
        {
            if (string.IsNullOrWhiteSpace(userInfo.id))//未取到Id 不进行插入
                return null;
            var result = SaveUser(userInfo);
            ZeppSaveAthlete(userInfo, result.Id);
            return result;
        }

        private SportUser SaveUser(ZeppUserInfo userInfo)
        {
            if (SportUserRepository.Exists(t => t.PartnerUserId == userInfo.id))
            {
                var sportUser = SportUserRepository.Find(t => t.PartnerUserId == userInfo.id).FirstOrDefault();
                ZeppUserInfoExtension.SetEntity(sportUser, userInfo);
                return sportUser;
            }
            var result = userInfo.ToSportUser();
            SportUserRepository.Add(result);
            return result;
        }

        private void ZeppSaveAthlete(ZeppUserInfo userInfo, Guid userId)
        {
            if (SportAthleteRepository.Exists(t => t.PartnerAthleteId == userInfo.id))
            {
                var sportAthlete = SportAthleteRepository.Find(t => t.PartnerAthleteId == userInfo.id).FirstOrDefault();
                ZeppUserInfoExtension.SetAthleteEntity(sportAthlete, userInfo);
                return;
            }
            SportAthleteRepository.Add(userInfo.ToAthlete(userId));
        }

        #endregion

        #region 输入导入

        /// <summary>
        /// 导入数据
        /// </summary>
        public void Import(SportUser user)
        {
            ImportTeam(user);
            ImportEvent(user);
        }

        #region 导入队伍

        /// <summary>
        /// 导入队伍
        /// </summary>
        private void ImportTeam(SportUser sportUser)
        {
            //获取我的球队
            var teamJson = Web.HttpPost(ZeppUrlConfig.GetTeams,
                new Dictionary<string, string>() { { "userId", sportUser.PartnerUserId } },
                new Dictionary<string, string>() { { "X-LC-Session", sportUser.Token } });
            var teams = Util.Json.ToObject<ZeppHttpResult<ZeppTeams>>(teamJson);
            foreach (var team in teams.result.memberedTeams)
                SaveTeam(team);
        }

        /// <summary>
        /// 保存队伍
        /// </summary>
        private void SaveTeam(ZeppTeam team)
        {
            SportTeamRepository.Add(team.ToSportTeam());
        }

        #endregion

        #region 导入比赛

        /// <summary>
        /// 导入比赛
        /// </summary>
        private void ImportEvent(SportUser sportUser)
        {
            //获取我的球队
            var eventJson = Web.HttpPost(ZeppUrlConfig.GetEvents,
                new Dictionary<string, string>() { { "includeDemo", "true" } },
                new Dictionary<string, string>() { { "X-LC-Session", sportUser.Token } });
            var events = Util.Json.ToObject<ZeppHttpResult<ZeppEvents>>(eventJson);
            foreach (var game in events.result.games)
            {
                ImportEventReport(sportUser, game);
            }
        }

        /// <summary>
        /// 导入比赛报告
        /// </summary>
        private void ImportEventReport(SportUser sportUser, ZeppEvent zepp)
        {
            if (SportEventRepository.Exists(t => t.PartnerEventId == zepp.id))
                return;
            //获取我的球队
            var eventJson = Web.HttpPost(ZeppUrlConfig.GetEventReport,
                new Dictionary<string, string>() { { "gameId", zepp.id } },
                new Dictionary<string, string>() { { "X-LC-Session", sportUser.Token } });
            var events = Util.Json.ToObject<ZeppHttpResult<ZeppEventReport>>(eventJson);
            var sportEvent = SaveSportEvent(events.result.game);
            SaveSportEventTeam(events.result.game, sportEvent);
        }

        /// <summary>
        /// 保存比赛表
        /// </summary>
        private SportEvent SaveSportEvent(ZeppEvent zeppEvent)
        {
            var sportEvent = zeppEvent.ToSportEvent();
            if (!SportEventRepository.Exists(t => t.PartnerEventId == zeppEvent.id))
                SportEventRepository.Add(sportEvent);
            return sportEvent;
        }

        /// <summary>
        /// 保存比赛分组
        /// </summary>
        private SportEventGroup SaveSportEventTeam(ZeppEvent zeppEvent, SportEvent sportEvent)
        {
            SportEventGroup sportEventGroup = new SportEventGroup(Guid.NewGuid());
            sportEventGroup.SportEventId = sportEvent.Id;
            sportEventGroup.SportTeamId = SportTeamRepository.Find(t => t.PartnerTeamId == zeppEvent.team.id)
                .FirstOrDefault()?.Id;
            SportEventGroupRepository.Add(sportEventGroup);
            return sportEventGroup;
        }

        #endregion

        #endregion
    }
}
